const Sequelize = require('sequelize');

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  'postgres://postgres:password@localhost:6432/postgres';

async function makeInviteorg(inviteOrg) {
  console.log('invite org member start', inviteOrg);
  if (inviteOrg.role === 'owner' || inviteOrg.role === 'guest') return;
  try {
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
    var res = await sequelize.query(
      'BEGIN;' +
        'INSERT INTO message( user_from, user_to, type, content, state) values (:userFrom, :userTo, :type, :content, :state); ' +
        'COMMIT;',
      {
        replacements: {
          userFrom: inviteOrg.create_by,
          userTo: inviteOrg.user_id,
          type: 'invite_org_member',
          content: JSON.stringify({
            org_member_id: inviteOrg.id,
            teams: inviteOrg.invite_info
          }),
          state: 'pending'
        }
      }
    );
    console.log('invite org member ok', inviteOrg);
    return res;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.makeInviteorg = makeInviteorg;
